import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'


import Login from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import Dashboard from '@/views/Dashboard.vue'
import UserList from '@/views/user/UserList.vue'
import OrderList from '@/views/order/OrderList.vue'
import ServiceList from '@/views/service/ServiceList.vue'
import StaffList from '@/views/staff/StaffList.vue'
import ReviewList from '@/views/review/ReviewList.vue'
import Profile from '@/views/Profile.vue'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '首页' }
      },
      {
        path: '/users',
        name: 'UserList',
        component: UserList,
        meta: { title: '用户管理', adminOnly: true }
      },
      {
        path: '/orders',
        name: 'OrderList',
        component: OrderList,
        meta: { title: '订单管理' }
      },
      {
        path: '/services',
        name: 'ServiceList',
        component: ServiceList,
        meta: { title: '服务管理' }
      },
      {
        path: '/staff',
        name: 'StaffList',
        component: StaffList,
        meta: { title: '人员管理', adminOnly: true }
      },
      {
        path: '/reviews',
        name: 'ReviewList',
        component: ReviewList,
        meta: { title: '评价管理' }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: Profile,
        meta: { title: '个人中心' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})


router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters.isAuthenticated

  if (to.meta.requiresAuth) {
    if (!isAuthenticated) {
      next('/login')
      return
    }
    

    if (to.meta.adminOnly && store.getters.userType !== 1) {
      next('/dashboard')
      return
    }
  }

  if (to.path === '/login' && isAuthenticated) {
    next('/dashboard')
    return
  }

  next()
})

export default router 